package com.itany.shop.tran.impl;

import com.itany.shop.exception.DataAccessException;
import com.itany.shop.exception.ServiceException;
import com.itany.shop.tran.TransactionManager;
import com.itany.shop.util.JDBCUtil;

/**
 * Author:shixiaojun@itany.com
 * Date:2022/4/14 14:18
 * Version:1.0-SNAPSHOT
 * Description:
 */
public class TransactionManagerImpl implements TransactionManager {
    @Override
    public void begin() throws ServiceException {
        try {
            JDBCUtil.getConnection().setAutoCommit(false);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException("事务开启失败");
        }
    }

    @Override
    public void commit() throws ServiceException {
        try {
            if(!JDBCUtil.getConnection().getAutoCommit()){
                JDBCUtil.getConnection().commit();
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException("事务提交失败");
        } finally {
            // 释放连接
            try {
                JDBCUtil.close();
            } catch (DataAccessException e) {
                throw new ServiceException(e.getMessage());
            }
        }
    }

    @Override
    public void rollback() throws ServiceException {
        try {
            if(!JDBCUtil.getConnection().getAutoCommit()){
                JDBCUtil.getConnection().rollback();
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException("事务提交失败");
        } finally {
            // 释放连接
            try {
                JDBCUtil.close();
            } catch (DataAccessException e) {
                throw new ServiceException(e.getMessage());
            }
        }
    }
}
